import * as types from '../store/mutation'
import api from '../api/host'

const state = {
  hostinfo: {
    id: '',
    name: '',
    ip: '',
    port: '',
    passwd: '',
    username: ''
  },
  hostsList: []
}
const actions = {
  getIndexHosts: function ({commit}) {
    api.getIndexHosts(function (res) {
      commit(types.GET_HOST_LIST, res)
    })
  },
  createHostUpdateIndex: function ({commit}, host) {
    commit(types.CREATE_HOST, host)
  },
  deleteHostUpdateIndex: function ({commit}, id) {
    commit(types.DELETE_HOST, id)
  }
}
const mutations = {
  [types.GET_HOST_LIST](state, res) {
    if (state.hostsList.length != 0) {
      state.hostsList = []
    }
    res.data.response.forEach(data => {
      state.hostsList.push(data)
    })
  },
  [types.CREATE_HOST](state, res) {
    let check_is_updated_data = false;
    state.hostsList.forEach(host => {
      if (host.id == res.id) {
        check_is_updated_data = true;
      }
    });
    if (!check_is_updated_data) {
      state.hostsList.push(res)
    }
  },
  [types.DELETE_HOST](state, id) {
    state.hostsList = state.hostsList.filter(host => {
      return host.id != id
    })
  }
}
const getters = {
  allHostsList: state => state.hostsList
}
export default {
  state,
  actions,
  mutations,
  getters
}
